package file_utils

import (
	"errors"
	"fmt"
	"hft/Database/admin/file"
	adminreq "hft/Http/Models/request/admin_req"
	"hft/Http/Services/base"
	dirdao "hft/Http/Services/dir/dir_dao"
	"hft/e"
	"hft/global"
	"hft/tools"
	"strings"
	"time"
)

// 判断是否超过了文件大小限制
func IsOverMaxFileLimit(size []*adminreq.FileUUID, max int) bool {
	for _, v := range size {
		if v.Size > max {
			return false
		}
	}
	return true
}

// 生成文件名
func GenerateFIleName(filename string, uuid string) string {

	var nowDir = strings.Join(strings.Split(time.Now().Format("2006-01-02"), "-"), "")

	var fileStr = strings.Split(filename, ".")

	newFilename := fmt.Sprintf("%s.%s", tools.Md5(fmt.Sprintf("%v%v", uuid, filename)), fileStr[1])

	return fmt.Sprintf("%s/%s/%s", global.OC_CONFIG.AliyunOSS.BasePath, nowDir, newFilename)
}

// 存储文件到数据库
func SaveFileToMysql(filename string, size int64, ossFilename string, fileType string, pid int, claims tools.BaseClaims) (err error) {
	account, err := base.FindAccount(claims, global.OC_DB)
	if err != nil {
		return err
	}

	var dir *file.Dir

	err = global.OC_DB.Model(&file.Dir{}).Where("account_id = ?", account.ID).Scopes(dirdao.FindDirLink(pid, global.OC_DB)).First(&dir).Error

	if err != nil {
		return errors.New(e.DirNotExist)
	}
	var file = &file.File{
		FileType:  fileType,
		FileSize:  int(size),
		GetUrl:    ossFilename,
		RealName:  filename,
		DirID:     dir.ID,
		DirLink:   fmt.Sprintf("%v%v,", dir.Link, dir.ID),
		AccountID: account.ID,
	}
	err = global.OC_DB.Create(&file).Error

	if err != nil {
		return errors.New(e.CreateFileFail)
	}

	return nil

}
